<template>
    <div class="orgEdit">
        <el-dialog width="600px" :title="types=='edit'?'编辑机构':'添加机构'" :visible.sync="state" :show-close="true" :close-on-click-modal="false" >
            <el-form :model="orgInf" ref="form" :rules="rules" class="demo-form-inline" label-width="105px">
                <el-form-item label="机构名称：" class="lineblock" prop="name">
                    <el-input v-model.trim="orgInf.name" placeholder="请填写机构名称"></el-input>
                </el-form-item>
                <el-form-item label="上级机构：" class="lineblock" prop="org">
                    <el-input type="input" v-model="parentName" placeholder="请选择上级机构" @focus="showMenu()"></el-input>
                    <div class="zTree_box model_ct">
                        <div id="thrTree1" style="display: none;">
                            <ul class="ztree orgTree1" id="orgTree1"></ul>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="机构负责人：" class="lineblock" prop="leaderUserName">
                    <el-select v-model="orgInf.leaderUserId" filterable placeholder="请选择机构负责人">
                        <el-option
                        v-for="item in options.leaderUserName"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                    <!-- <el-input v-model="orgInf.leaderUserName" placeholder="请填写机构负责人"></el-input> -->
                </el-form-item>
                <el-form-item label="备注：" class="lineblock textareaBox remark" prop="remark">
                    <el-input type="textarea" v-model="orgInf.remark" placeholder="请填写备注"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary"
                @click="enSure"
                size="small">确 定</el-button>
                <el-button @click="state = false" size="small">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import {officesUrl,officesHandleUrl} from "../../../axios/api.js"
/*树形插件----开始*/
import vbootstrapStyle from '../../../../static/css/bootstrapStyle.css'
import vZtreeCore from '../../../../static/js/jquery.ztree.core.js'
import vZtreeExcheck from '../../../../static/js/jquery.ztree.excheck.js'
export default {
  data() {
    return {
        inItPageList:[],
        leaderUserName:[],
        state: false,
        types:'',
        orgInf:{
            id:'',
            name:'',
            leaderUserId:'',
            remark:'',
            parentId:null
        },
        zTreeData : [],
        isZTree : false,
        selects:[
            {value:1},
            {value:2},
            {value:3},
            {value:4},
            {value:5},
            {value:6}
        ],
        parentName:'',
        cascaderOptions:[],
        rules:{
            name: [
                { required: true, message: '机构名称不能为空', trigger: 'blur'},
                { max: 20, message: "机构名称不能超过20个字符", trigger: "blur" },
            ],
            remark:[
                { max: 50, message: "备注信息不能超过50个字符", trigger: "blur" },
            ]
        },
        options:{
            leaderUserName:[]
        }

    };
  },
  created() {

  },
  mounted() {

  },
  methods: {
    // 打开模态框
    showDialog(val,type,spreadId){
        this.state = true;
        let self = this;

        self.types=type;
        self.orgInf.id="";
        self.orgInf.name="";
        self.orgInf.remark="";
        self.orgInf.parentId = '';
        self.parentName = "";

        self.$nextTick(function(){
            this.$refs['form'].resetFields();
            if($.fn.zTree.getZTreeObj("thrTree1")){
                $.fn.zTree.getZTreeObj("thrTree1").checkAllNodes(false);
            }
        })

        // 是否获取用户信息
        if(type == 'edit'){
            // 获取用户信息
            self.axios({
                method: "get",
                url: officesHandleUrl + val
            })
            .then(function(response) {
                // 更新本地信息
                self.orgInf.id = val;
                self.orgInf.name = response.data.data.name;
                self.orgInf.remark = response.data.data.remark;
                self.orgInf.parentId = response.data.data.parentId;
                self.parentName = response.data.data.parentName;
                self.parentId = response.data.data.parentId;

                if(response.data.data.leaderUserId){
                    self.orgInf.leaderUserId = parseInt(response.data.data.leaderUserId)
                }
            })
        }else{
            self.orgInf.parentId = spreadId;
        }
        self.zTreeEdit();
        self.getUserAll();
    },
    zTreeEdit(){
        let self = this;
        var setting = {
            view: {
                dblClickExpand: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback:{
              //点击事件
              onClick: zTreeOnClick,
              onCheck: zTreeCheck,
            }
        };

        self.axios({
            method: "get",
            url: self.axios.defaults.baseURL + "/offices/treeContainDj"
        })
        .then(function(response) {
            var zNodes = [];
            zNodes.push(response.data.data);
            if(self.types == 'add'){
                var parentItem = self.getName(zNodes,self.orgInf.parentId);
                self.parentName = parentItem.name;
            }
            // 初始化树形结构
            $.fn.zTree.init($("#orgTree1"), setting, zNodes);
        })

        function zTreeOnClick(e, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var node = treeObj.getNodeByTId(treeNode.tId);
            self.orgInf.parentId = node.id;
            self.parentName = node.name;
            self.hideMenu();
        };
        // 定义勾选事件
        function zTreeCheck(event, treeId, treeNode) {
            var treeObj = $.fn.zTree.getZTreeObj(treeId);
            var node = treeObj.getNodeByTId(treeNode.tId);
            self.parentName = node.name
            self.orgInf.parentId = node.id
            self.isZTree = !self.isZTree;
        };
    },
    onBodyDown(event) {
        let self = this;
        if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || event.target.id == "thrTree1" || $(event.target).parents("#thrTree1").length>0)) {
            self.hideMenu();
        }
    },
    showMenu() {
        let self = this;
        var cityObj = $("#thrTree1");
        var cityOffset = $("#thrTree1").offset();
        $("#thrTree1").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");

        $("body").bind("mousedown", self.onBodyDown);
        return false;
    },
    hideMenu() {
        let self = this;
        $("#thrTree1").fadeOut("fast");
        $("body").unbind("mousedown", self.onBodyDown);
        return false;
    },
    //显示树结构
    showTree(){
        this.isZTree = !this.isZTree;
    },
    getUserAll(){
        let self = this;
        // 发送请求
        self.axios({
            method: "get",
            url: api.userAllListUrl
        })
        .then(function(response) {
            if(response.data.success){
                self.options.leaderUserName = response.data.data;
            }else{
                // 操作失败
                self.$message({
                    message: response.data.msg,
                    type:'error',
                    center: true
                });
            }
        })
    },
    putUserArr(params){
        let self = this;
        let nameStr = '';
        var userArr = [];
        _.forEach(params,function(item,index){
            let userItem = {};
            userItem.id = item.id;
            userItem.name = item.name;
            userArr.push(userItem);

            //显示名字
            nameStr = nameStr + item.name + ','
        })
        this.leaderUserName = userArr;
        this.orgInf.leaderUserName = nameStr;
    },
    //  返回对象
    getName(json, id) {
        for (var i = 0; i < json.length; i++) {
            var model = json[i];
            if (model.id == id) {
                return model;
            }
            if (model.child != null && model.child.length > 0) {
                var name = this.getName(model.child, id);
                if (name != null) {
                    return name;
                }
            }
        }
        return null;
    },
    // 点击确定提交
    enSure(){
        let self = this;
        this.$refs['form'].validate((valid) => {
            if (valid) {
                let Type = self.types;
                let currentMethod ='';
                let currentUrl ='';
                let currentData ='';
                let currentId = self.orgInf.id;
                // 根据传入路径中是否有id，书写不同接口提交的信息
                if(self.types == 'edit'){                  //修改
                    currentMethod = "put";
                    currentUrl = officesHandleUrl + self.orgInf.id;
                    currentData = self.orgInf
                }else{                                     //新增
                    currentMethod = "post";
                    currentUrl = officesUrl;
                    // self.orgInf.parentId = self.parentId;
                    delete self.orgInf["id"]
                    currentData = self.orgInf
                }
                // 发送请求
                self.axios({
                    method: currentMethod,
                    url: currentUrl,
                    data: currentData
                })
                .then(function(response) {
                    if(response.data.success){
                        // 操作成功
                        self.$message({
                            message: response.data.msg,
                            type:'success',
                            center: true
                        });
                        self.state = false;
                        // 更改树节点
                        if(self.types == 'edit'){                  //修改
                            self.$parent.updateTreeNode(currentData);
                        }else{                                     //新增
                            self.$parent.addTreeNode(response.data.data);
                        }
                        self.$parent.DetailsData(self.parentId,'机构')
                    }else{
                        // 操作失败
                        self.$message({
                            message: response.data.msg,
                            type:'error',
                            center: true
                        });
                    }
                })
            }
        })
    }
  }
};
</script>
<style scoped>
    .model_ct{width: 100%; position: absolute; top: 33px ;left:0; background: #FFF; z-index: 10; }
    #thrTree1{ padding: 10px; max-height:200px; overflow-y: auto; border-radius: 4px; border: 1px solid #dedede;}
    .orgEdit .el-select{width: 100%;}

</style>